package com.xbts.system.module.sms;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.xbts.common.config.SmsAliTemplateConfig;
import com.xbts.common.constant.Constants;
import com.xbts.common.core.domain.Setting;
import com.xbts.common.core.redis.RedisCache;
import com.xbts.common.enums.SettingEnum;
import com.xbts.common.enums.SmsTemplateEnum;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.dto.SmsAliSetting;
import com.xbts.system.domain.dto.SmsDTO;
import com.xbts.system.service.SettingService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ALiYunSmsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ALiYunSmsUtil.class);

    @Autowired
    private SettingService settingService;

    @Autowired
    private SmsAliTemplateConfig smsAliTemplateConfig;

    @Autowired
    private RedisCache redisCache;

    /**
     * 发送短息
     *
     * @param smsDTO 参数
     * @return
     */
    public String sendMsg(SmsDTO smsDTO, SmsTemplateEnum smsTemplateEnum, int timeOut) {
        String phone = smsDTO.getPhone();
        String param = smsDTO.getContent();
        //模版 默认为登录验证
        String templateCode = null;
        switch (smsTemplateEnum){
            case REGISTER:
                templateCode = smsAliTemplateConfig.getREGISTER();
                break;
            case EXPIRATION_NOTICE:
                templateCode = smsAliTemplateConfig.getEXPIRATION_NOTICE();
                break;
        }
        Map<String, String> params = new HashMap<>(2);
        String smsVerificationCode = null;
        if (StringUtils.isEmpty(param)){
            smsVerificationCode = StringUtils.getRandomNum();
            //准备发送短信参数
            //验证码内容
            params.put("code", smsVerificationCode);
        }


        Setting setting = settingService.get(SettingEnum.SMS_ALI_SETTING.name());
        SmsAliSetting smsAliSetting = null;
        if (setting != null) {
            smsAliSetting = JSONObject.parseObject(setting.getSettingValue(), SmsAliSetting.class);
        }
        if (null == smsAliSetting) {
            throw new ServiceException("请配置阿里云短信服务商信息");
        }
        String key = smsAliSetting.getAccessKeyId();
        String secret = smsAliSetting.getAccessSecret();
        String signName = smsAliSetting.getSignName();

        Config config = new Config()
                //这里修改为我们上面生成自己的AccessKey ID
                .setAccessKeyId(key)
                //这里修改为我们上面生成自己的AccessKey Secret
                .setAccessKeySecret(secret);
        try {
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(signName)//短信签名
                    .setTemplateCode(templateCode)//短信模板
                    .setPhoneNumbers(phone);//这里填写接受短信的手机号码
            if (ObjectUtils.isNotEmpty(param)) {
                //参数  "{\"code\":\""+code+"\"}"
//                sendSmsRequest.setTemplateParam(param);
                sendSmsRequest.setTemplateParam(JSONObject.toJSONString(params));
            } else { // 短信验证码
                sendSmsRequest.setTemplateParam(JSONObject.toJSONString(params));
                redisCache.setCacheObject(Constants.SMS + smsTemplateEnum.name() + phone, smsVerificationCode, timeOut, TimeUnit.MINUTES);
            }
            // 复制代码运行请自行打印 API 的返回值
            return client.sendSms(sendSmsRequest).getBody().getMessage();
        } catch (Exception e) {
            LOGGER.error("阿里云短信发送异常" + e);
        }
        return null;
    }

}
